﻿package  KK.Queue{
	import KK.Queue.IQueueObject;
	import KK.net.Q_AMFLoader;

	public class Queue implements IQueue{
		
		private var _queue:Vector.<IQueueObject>;//队列
		private var _priority_queue:Vector.<IQueueObject>;//优先队列
		private var _current_queue:Vector.<IQueueObject>;//当前队列
		private var max:int;//最大同时队列
		private var current:int//当前队列数
		
		public function Queue(max:int=1) :void{
			// constructor code
			Max=max;
			init();
		}
		private function init():void
		{
			_queue=new Vector.<IQueueObject>;
			_priority_queue=new Vector.<IQueueObject>;
			_current_queue=new Vector.<IQueueObject>;
			
		}
		public function set Max(max:int):void{
			this.max=max
		}
		public function get Max():int{
			return this.max;
		}
		//添加队列
		protected function AddQueue(QObject:IQueueObject):void
		{
			_queue.push(QObject);
			checkStart();
		}
		//添加优先列队
		protected function AddPriority(QObject:IQueueObject):void
		{
			_priority_queue.push(QObject);
			checkStart();
		}
		//移除队列的QObject对象；
		public function RemoveQueue(QObject:IQueueObject):Boolean
		{
			var count:int=_queue.length;
			var result:Boolean=false;
			var i:int=0;
			for(i=0;i<_queue.length;i++)
			{
				if(_queue[i]==QObject)
				{
					QObject.Reset();
					_queue.splice(i,1);
					result=true;
					break;
				}
			}
			for(i=0;i<_priority_queue.length;i++)
			{
				if(_priority_queue[i]==QObject)
				{
					QObject.Reset();
					_priority_queue.splice(i,1);
					result=true;
					break;
				}
			}
			checkStart();
			return result;
		}
		//完成并且移除当前队列
		public function Complete(QObject:IQueueObject):void
		{
			var i:int=0;
			for(i=0;i<current;i++)
			{
				if(_current_queue[i]==QObject)
				{
					QObject.Reset();
					_current_queue.splice(i,1);
					current--;
					break;
				}
			}
			checkStart();
		}
		
		//检查并开始队列
		private function checkStart():void{
			if(current<max)
			{
				if(_priority_queue.length>0)
				{
					current++;
					_priority_queue[0].Run(this);
					_current_queue.push(_priority_queue[0]);
					_priority_queue.shift();
				}else if(_queue.length>0){
					current++;
					_queue[0].Run(this);
					_current_queue.push(_queue[0]);
					_queue.shift();
				}
			}
		} 
	}
	
}
